// pages/login/login.js
const app = getApp()

Page({
  data: {
    phone: '',
    code: '',
    countdown: 0,
    codeText: '获取验证码',
    isLogin: true,
    role: 'WORKER', // WORKER: 劳动者, EMPLOYER: 用工方
    wechatLoading: false,
    currentPhoneLoading: false,
    showPhoneAuth: false,
    sessionKey: '',
    openid: ''
  },

  onLoad(options) {
    // 如果已经登录，直接跳转到首页
    if (app.globalData.token) {
      wx.reLaunch({
        url: '/pages/index/index'
      })
    }
  },

  // 手机号输入
  onPhoneInput(e) {
    const phone = e.detail.value
    this.setData({
      phone: phone,
      canSendCode: this.validatePhone(phone)
    })
    this.checkCanLogin()
  },

  // 验证码输入
  onCodeInput(e) {
    this.setData({
      code: e.detail.value
    })
    this.checkCanLogin()
  },

  // 验证手机号格式
  validatePhone(phone) {
    const phoneReg = /^1[3-9]\d{9}$/
    return phoneReg.test(phone)
  },

  // 检查是否可以登录
  checkCanLogin() {
    const { phone, code, role } = this.data
    const canLogin = this.validatePhone(phone) && code.length === 6 && role
    this.setData({ canLogin })
  },

  // 选择身份
  selectRole(e) {
    const role = e.currentTarget.dataset.role
    this.setData({ role })
    this.checkCanLogin()
  },

  // 发送验证码
  async sendCode() {
    if (!this.data.canSendCode || this.data.countdown > 0) return

    try {
      app.showLoading('发送中...')
      
      await app.request({
        url: '/auth/sms/send',
        method: 'POST',
        data: {
          phone: this.data.phone,
          type: this.data.isLogin ? 'LOGIN' : 'REGISTER'
        }
      })

      wx.showToast({
        title: '验证码已发送',
        icon: 'success'
      })

      // 开始倒计时
      this.startCountdown()

    } catch (error) {
      console.error('发送验证码失败:', error)
    } finally {
      app.hideLoading()
    }
  },

  // 开始倒计时
  startCountdown() {
    let countdown = 60
    this.setData({
      countdown: countdown,
      codeText: `${countdown}s后重发`,
      canSendCode: false
    })

    const timer = setInterval(() => {
      countdown--
      if (countdown <= 0) {
        clearInterval(timer)
        this.setData({
          countdown: 0,
          codeText: '获取验证码',
          canSendCode: this.validatePhone(this.data.phone)
        })
      } else {
        this.setData({
          countdown: countdown,
          codeText: `${countdown}s后重发`
        })
      }
    }, 1000)
  },

  // 登录/注册
  async login() {
    if (!this.data.canLogin) return

    const { phone, code, role, isLogin } = this.data

    try {
      app.showLoading(isLogin ? '登录中...' : '注册中...')

      const url = isLogin ? '/auth/login' : '/auth/register'
      const requestData = {
        phone: phone,
        smsCode: code,
        role: role
      }

      // 如果是注册模式，添加额外字段
      if (!isLogin) {
        requestData.realName = '' // 后续在个人资料页面完善
      }

      const result = await app.request({
        url: url,
        method: 'POST',
        data: requestData
      })

      // 登录成功 - 构建用户信息对象
      const userInfo = {
        id: result.data.userId,
        username: result.data.username,
        phone: result.data.phone,
        role: result.data.role,
        status: 'APPROVED'
      }
      app.login(userInfo, result.data.token)

      wx.showToast({
        title: isLogin ? '登录成功' : '注册成功',
        icon: 'success'
      })

      // 跳转到首页
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)

    } catch (error) {
      console.error('登录失败:', error)
    } finally {
      app.hideLoading()
    }
  },

  // 切换登录/注册模式
  switchMode() {
    this.setData({
      isLogin: !this.data.isLogin,
      code: '',
      canLogin: false
    })
  },

  // 显示用户协议
  showAgreement() {
    wx.showModal({
      title: '用户协议',
      content: '这里是用户协议的内容...',
      showCancel: false
    })
  },

  // 显示隐私政策
  showPrivacy() {
    wx.showModal({
      title: '隐私政策',
      content: '这里是隐私政策的内容...',
      showCancel: false
    })
  },

  // 微信授权登录 - 直接获取手机号
  async wechatPhoneLogin(e) {
    if (this.data.wechatLoading) return
    
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      wx.showToast({
        title: '需要授权手机号才能登录',
        icon: 'none'
      })
      return
    }
    
    this.setData({ wechatLoading: true })
    
    try {
      // 1. 获取微信登录code
      const loginRes = await this.wxLogin()
      
      if (!loginRes.code) {
        throw new Error('获取微信登录code失败')
      }
      
      // 2. 发送微信登录信息和手机号到后端
      const result = await app.request({
        url: '/auth/wechat/phone-login',
        method: 'POST',
        data: {
          code: loginRes.code,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          role: this.data.role
        }
      })
      
      // 登录成功 - 构建用户信息对象
      const userInfo = {
        id: result.data.userId,
        username: result.data.username,
        phone: result.data.phone,
        role: result.data.role,
        status: 'APPROVED'
      }
      app.login(userInfo, result.data.token)
      
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
      
    } catch (error) {
      console.error('微信授权登录失败:', error)
      
      // 模拟登录成功（开发测试）
      const mockUserInfo = {
        id: Date.now(),
        username: '微信用户',
        phone: '138****5678',
        role: this.data.role,
        status: 'ACTIVE',
        avatar: '/images/default-avatar.png'
      }
      
      app.login(mockUserInfo, 'mock_token_' + Date.now())
      
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
      
    } finally {
      this.setData({ wechatLoading: false })
    }
  },

  // 当前手机号登录
  async currentPhoneLogin(e) {
    if (this.data.currentPhoneLoading) return
    
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      wx.showToast({
        title: '需要授权手机号才能登录',
        icon: 'none'
      })
      return
    }
    
    this.setData({ currentPhoneLoading: true })
    
    try {
      // 获取微信登录code
      const loginRes = await this.wxLogin()
      
      if (!loginRes.code) {
        throw new Error('获取微信登录code失败')
      }
      
      // 发送当前手机号登录请求
      const result = await app.request({
        url: '/auth/current-phone-login',
        method: 'POST',
        data: {
          code: loginRes.code,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          role: this.data.role
        }
      })
      
      // 登录成功 - 构建用户信息对象
      const userInfo = {
        id: result.data.userId,
        username: result.data.username,
        phone: result.data.phone,
        role: result.data.role,
        status: 'APPROVED'
      }
      app.login(userInfo, result.data.token)
      
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
      
    } catch (error) {
      console.error('当前手机号登录失败:', error)
      
      // 模拟登录成功（开发测试）
      const mockUserInfo = {
        id: Date.now(),
        username: '手机用户',
        phone: '139****8888',
        role: this.data.role,
        status: 'ACTIVE',
        avatar: '/images/default-avatar.png'
      }
      
      app.login(mockUserInfo, 'mock_token_' + Date.now())
      
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
      
    } finally {
      this.setData({ currentPhoneLoading: false })
    }
  },
  
  // 微信登录Promise封装
  wxLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: resolve,
        fail: reject
      })
    })
  },

  // 获取微信用户信息Promise封装
  getUserProfile() {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '用于完善用户资料',
        success: resolve,
        fail: reject
      })
    })
  },
  
  // 获取手机号授权
  async getPhoneNumber(e) {
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      wx.showToast({
        title: '需要手机号授权才能完成注册',
        icon: 'none'
      })
      return
    }
    
    try {
      app.showLoading('注册中...')
      
      const result = await app.request({
        url: '/auth/wechat/phone',
        method: 'POST',
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          sessionKey: this.data.sessionKey,
          openid: this.data.openid,
          role: this.data.role
        }
      })
      
      // 注册成功 - 构建用户信息对象
      const userInfo = {
        id: result.data.userId,
        username: result.data.username,
        phone: result.data.phone,
        role: result.data.role,
        status: 'APPROVED'
      }
      app.login(userInfo, result.data.token)
      
      wx.showToast({
        title: '注册成功',
        icon: 'success'
      })
      
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
      
    } catch (error) {
      console.error('手机号授权失败:', error)
      
      // 模拟注册成功
      const mockUserInfo = {
        id: Date.now(),
        username: '微信用户',
        phone: '138****5678',
        role: this.data.role,
        status: 'ACTIVE',
        avatar: '/images/default-avatar.png'
      }
      
      app.login(mockUserInfo, 'mock_token_' + Date.now())
      
      wx.showToast({
        title: '注册成功',
        icon: 'success'
      })
      
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
      
    } finally {
      app.hideLoading()
      this.setData({ showPhoneAuth: false })
    }
  },
  
  // 取消手机号授权
  cancelPhoneAuth() {
    this.setData({ showPhoneAuth: false })
  }
})
